package com.xw.qxypt.modules.controller;


import com.xw.qxypt.modules.util.HspUtil;
import com.xw.qxypt.modules.util.R;
import com.xw.qxypt.modules.util.XwSocketUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("socket")
public class SocketController {


    //发送AT指令
    @RequestMapping("/sendInstruction")
    private R sendInstruction(@RequestParam Map<String, Object> params){
        String pointCode= (String) params.get("pointCode");
        String sendMessage= (String) params.get("sendMessage");
        if (HspUtil.map.containsKey(pointCode) && HspUtil.map.get(pointCode).getSocket() != null){
            try {
                Socket ses = HspUtil.map.get(pointCode).getSocket();
                String sendHexStr = XwSocketUtil.str2HexStr(sendMessage);
                sendHexStr += "0D0A";
                XwSocketUtil.sendData(sendHexStr, ses.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }

    //接收AT指令
    @RequestMapping("/receiveInstruction")
    private R receiveInstruction(@RequestParam Map<String, Object> params){
        String pointCode= (String) params.get("pointCode");
        String receiveMessage= "";
        if (HspUtil.dtuMap.containsKey(pointCode) && HspUtil.dtuMap.get(pointCode)!= null){
            receiveMessage= HspUtil.dtuMap.get(pointCode);
            HspUtil.dtuMap.put(pointCode,null);
        }
        return R.ok().put("message",receiveMessage);
    }

    // 查询连接状态
    @RequestMapping("/getSocketStatus/{pointCode}")
    public R getSocketStatus(@PathVariable("pointCode") String pointCode) {
        String status="未连接";
        if (HspUtil.map.containsKey(pointCode) && HspUtil.map.get(pointCode).getSocket() != null) {
            status="已连接";
        }
        return R.ok().put("status",status);
    }
    //关闭连接
    @RequestMapping("/closeSocket/{pointCode}")
    public R closeSocket(@PathVariable("pointCode") String pointCode) {
        if (HspUtil.map.containsKey(pointCode)) {
            Socket clientSocket = HspUtil.map.get(pointCode).getSocket();
            if(clientSocket != null){
                try{
                    clientSocket.close();
                    System.out.println("关闭"+pointCode+"链接！");
                }catch(Exception e){

                }
            }
        }
        return R.ok();
    }

}
